package com.monkeygroup.mygoplus.view.entrance.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyAlertDialog;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.view.entrance.activity.RegisterPrivacyActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by cumt on 2017/3/9.
 */

public class RegisterFragment  extends Fragment implements View.OnClickListener{

    public static RegisterFragment getInstance(String loginFlg) {
        RegisterFragment f = new RegisterFragment();
        Bundle bundle = new Bundle();
        bundle.putString("loginFlg", loginFlg);//判断是否为三方注册
        f.setArguments(bundle);

        return f;
    }


    private String loginFlg;

    private Activity activity;
    //头部
    private TextView txtTitle;
    private ImageView imgBack;

    // Fragment管理对象
    private FragmentManager manager;
    private FragmentTransaction ft;

    private EditText et;
    private TextView btn_register_ok,txtPrefix,txt_privacy;

    private Spinner rigiterspinner;
    private ArrayAdapter<String> adapter;

    //請求參數
    private Map<String, String> params;
    private HttpModel httpModel;


    private View mView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        activity = getActivity();
        manager = getFragmentManager();

        if (mView == null) {

            mView = inflater.inflate(R.layout.fragment_register, container, false);


            initView();
            initListener();
            initRequest();
        }
        return mView;
    }

    private void initView() {

        loginFlg = getArguments().getString("loginFlg");

        txtTitle =  (TextView)mView.findViewById(R.id.txt_title);
        txtTitle.setText("手機認證註冊");
        imgBack =  (ImageView) mView.findViewById(R.id.img_back);


        btn_register_ok = (TextView)mView.findViewById(R.id.btn_register_ok);
        rigiterspinner= (Spinner) mView.findViewById(R.id.rigiterspinner);

        String[] items = getResources().getStringArray(R.array.area);
        adapter = new ArrayAdapter<String>(activity, R.layout.myspinner,items);
        rigiterspinner.setAdapter(adapter);


        et =  (EditText) mView.findViewById(R.id.register_et_next);
        txtPrefix =  (TextView)mView.findViewById(R.id.txt_prefix);

        params = new HashMap<>();

        txt_privacy =  (TextView)mView.findViewById(R.id.txt_privacy);

        txt_privacy.setHighlightColor(getResources().getColor(android.R.color.transparent));//去掉点击后的蓝色背景

       String detail= getString(R.string.register_detail);
        String privacy= getString(R.string.register_privacy_I);
        String privacy1= getString(R.string.register_privacy_II);
        String privacy2= getString(R.string.register_privacy_III);

        SpannableString s = new SpannableString(detail);

        Pattern p = Pattern.compile(privacy);
        Matcher m = p.matcher(s);

        while (m.find()) {
            int start = m.start();
            int end = m.end();
            s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            s.setSpan(new Clickable(clickListener), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
          //  type=1;
        }

        Pattern p1 = Pattern.compile(privacy1);
        Matcher m1 = p1.matcher(s);

        while (m1.find()) {
            int start = m1.start();
            int end = m1.end();
            s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            s.setSpan(new Clickable(clickListener1), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        Pattern p2 = Pattern.compile(privacy2);
        Matcher m2 = p2.matcher(s);

        while (m2.find()) {
            int start = m2.start();
            int end = m2.end();
            s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            s.setSpan(new Clickable(clickListener2), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }


        txt_privacy.setText(s);
        txt_privacy.setMovementMethod(LinkMovementMethod.getInstance());



    }

    private View.OnClickListener clickListener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {

          //  Toast.makeText(activity, "点击成功....",Toast.LENGTH_SHORT).show();
//            txt_privacy.setTextColor();
            RegisterPrivacyActivity.gotoActivity(activity,1);
        }
    };

    private View.OnClickListener clickListener1=new View.OnClickListener() {
        @Override
        public void onClick(View v) {

           // Toast.makeText(activity, "点击成功1....",Toast.LENGTH_SHORT).show();
            RegisterPrivacyActivity.gotoActivity(activity,2);
        }
    };

    private View.OnClickListener clickListener2=new View.OnClickListener() {
        @Override
        public void onClick(View v) {

           // Toast.makeText(activity, "点击成功2....",Toast.LENGTH_SHORT).show();
            RegisterPrivacyActivity.gotoActivity(activity,3);

        }
    };

    class Clickable extends ClickableSpan {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener l) {
            mListener = l;
        }

        /**
         * 重写父类点击事件
         */
        @Override
        public void onClick(View v) {
            mListener.onClick(v);
        }

        /**
         * 重写父类updateDrawState方法  我们可以给TextView设置字体颜色,背景颜色等等...
         */
        @Override
        public void updateDrawState(TextPaint ds) {
           // ds.setColor(getResources().getColor(R.color.font_gray_II));
        }
    }

    private void initListener() {

        mView.findViewById(R.id.btn_register_ok).setOnClickListener(this);

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getFragmentManager().popBackStack();
            }
        });

        rigiterspinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Log.e("ArrayAdadapter===",""+adapter.getItem(position));
                if(position==0){
                    txtPrefix.setText("+886");
                }
                else if(position==1){
                    txtPrefix.setText("+86");
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }


        });

        et.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {


                if (VilidateUtil.isMobile(String.valueOf(et.getText()))) {



                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(et.getWindowToken(), 0) ;

                    params.put("mobile",String.valueOf(et.getText()));
                    httpModel.startRequest();

                }
                else{
                    btn_register_ok.setBackgroundResource(0);
                    btn_register_ok.setBackgroundResource(R.drawable.btn_grey_shape);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {



            }
        });

    }


    private void initRequest(){

         httpModel = new HttpModel(RequestUrl.baseUrl+RequestUrl.vilidateUrl,params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {

                Map<String,String> result = (HashMap)data;

                if (Double.parseDouble(String.valueOf(result.get("isSignUp")))==1) {

                    MyAlertDialog dialog = new MyAlertDialog(activity,"該手機已經註冊過了","");
                    dialog.show(activity,"該手機已經註冊過了",1);
                    return;
                }
                else{

                    btn_register_ok.setBackgroundResource(0);
                    btn_register_ok.setBackgroundResource(R.drawable.btn_red_shape);


                }


            }
        },true);







    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_register_ok:
                boolean isread = btn_register_ok.getBackground().getCurrent().getConstantState().equals(getResources().getDrawable(R.drawable.btn_red_shape).getCurrent().getConstantState());

                if(!isread){
                    if(loginFlg.equals("thirdLogin")){
                        RegitsterCodeFragment register = RegitsterCodeFragment.getInstance(String.valueOf(et.getText()),"2","thirdLogin");
                        ft = manager.beginTransaction();
                        //当前的fragment会被RegisterFragment替换
                        ft.replace(R.id.fragment_container, register);
                        ft.addToBackStack(null);
                        ft.commit();
                    }else{
                        RegitsterCodeFragment register = RegitsterCodeFragment.getInstance(String.valueOf(et.getText()),"2","normalRegister");
                        ft = manager.beginTransaction();
                        //当前的fragment会被RegisterFragment替换
                        ft.replace(R.id.fragment_container, register);
                        ft.addToBackStack(null);
                        ft.commit();
                    }

                }

                break;



        }



    }




}
